#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:ZSW
@file:MinioBucketBase.py
@time:2020/12/04
"""
import base64
import json
import os

from datasource.minio_config import minioClient, Bucket
import binascii


from django.http import StreamingHttpResponse,Http404,HttpResponse,JsonResponse

from datasource.models import PictureList


def bucketinfo(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        mino_client = Bucket()
        res = mino_client.create_bucket(data['bucketName'])
        if(1 == res):
           return JsonResponse({"data":{'a':100},"msg":'存储桶已存在新建失败','code':3000})
        else:
          return JsonResponse({"data":{'a':100},"msg":'新建成功','code':2000})
    if request.method == 'GET':
        mino_client = Bucket()
        bucket_list = []
        buckets = minioClient.list_buckets()
        for bucket in buckets:
            bucket_infomation = {}
            bucket_infomation['name'] = bucket.name
            ct = bucket.creation_date
            bucket_infomation['time'] = str(ct.year)+'-'+str(ct.month)+'-'+str(ct.day) + ' ' +str(ct.hour)+':'+str(ct.minute)+':'+str(ct.second)
            bucket_infomation['size'] = mino_client.get_bucket_size(bucket.name)
            objects = minioClient.list_objects(bucket.name, recursive=True)
            # 计算对象数量，即文件数量
            num_files = len([obj for obj in objects])
            bucket_infomation['filecount'] = num_files
            bucket_list.append(bucket_infomation)
        return JsonResponse({"data":{'data':bucket_list},"msg":'查询成功','code':2000})
    if request.method == 'DELETE':
        mino_client = Bucket()
        data = json.loads(request.body.decode('utf-8'))
        bucket_name = data['bucketName']
        try:
            mino_client.get_remove_bucket(bucket_name)
            return JsonResponse({"data":[],"msg":'删除成功','code':2000})
        except :
            return JsonResponse({"data":[],"msg":'桶内存有文件，不能删除','code':4000})

def getbucketall(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        objects = minioClient.list_objects(data['name'],recursive=True)
        picture_list = []
        for obj in objects:
            response =  minioClient.get_object(data['name'], obj.object_name)
            base64_str = base64.b64encode(response.data).decode('utf-8')
            #bucket_name  content_type  object_name size version_id
            obj_info = {}
            obj_info['bucket_name'] = obj.bucket_name
            obj_info['content_type'] = obj.content_type
            obj_info['object_name'] = obj.object_name
            obj_info['size'] = obj.size
            obj_info['version_id'] = obj.version_id
            picture_list.append(obj_info)
        return JsonResponse({"data": {'data': picture_list}, "msg": '获取成功', 'code': 2000})
def deletebucketall(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        object_list = data['info']
        for obj in object_list:
            try:
                pic = PictureList.objects.get(name=obj['object_name'])
                pic.delete()
            except :
                pass
            minioClient.remove_object(obj['bucket_name'], obj['object_name'])
    return JsonResponse({"data": {'data': data}, "msg": '删除成功', 'code': 2000})
def getone(request):
    if request.method == 'GET':
        image_name = request.request_data['name']
        bucket_name = request.request_data['src']
        path = f'C:/Users/hsj/PycharmProjects/a/cv_platform/media/files/{bucket_name}/'
        folder = os.path.exists(path)
        if not folder:
            os.makedirs(path)
            print('已创建新文件夹')

        else:
            print('文件夹已存在')
        response = minioClient.get_object(bucket_name, image_name)
        file = open(path+image_name,'wb')
        file.write(response.data)
        file.close()
    return JsonResponse({"data": {'data': {'name': image_name,'path':f'media/files/{bucket_name}/{image_name}'}}, "msg": '查询成功', 'code': 2000})

def getmore(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        print(data['data'])
        pathinfo = []
        for pic in data['data']:
            image_name = pic['name']
            bucket_name = pic['src']
            picinfo ={}
            path = f'C:/Users/hsj/PycharmProjects/a/cv_platform/media/files/{bucket_name}/'
            folder = os.path.exists(path)
            if not folder:
                os.makedirs(path)
                print('已创建新文件夹')

            else:
                print('文件夹已存在')
            response = minioClient.get_object(bucket_name, image_name)
            file = open(path+image_name,'wb')
            file.write(response.data)
            file.close()
            picinfo['name'] = image_name
            picinfo['path'] = f'media/files/{bucket_name}/{image_name}'
            pathinfo.append(picinfo)
    return JsonResponse({"data": {'data': pathinfo}, "msg": '查询成功', 'code': 2000})
